﻿(function () {
    "use strict";

    function getGroupInfoFromXml(articleSyndication, feed) {
        // Get the blog title and last updated date.
        if (articleSyndication.querySelector("feed") != null) {
            feed.title = articleSyndication.querySelector(
                "feed > title").textContent;
            var ds = articleSyndication.querySelector(
                "feed > updated").textContent;
            var date = ds.substring(5, 7) + "-" + ds.substring(8, 10) + "-" + ds.substring(0, 4);
            var author = articleSyndication.querySelector(
                "author > name").textContent;
            feed.description = "Por " + author + " actualizado " + date;
            feed.subtitle = articleSyndication.querySelector("feed > title").textContent;

            feed.itemsName = "entry";
        } else if (articleSyndication.querySelector("channel") != null) {
            feed.title = articleSyndication.querySelector(
                "channel > title").textContent;
            if (articleSyndication.querySelector("channel > pubDate") != null)
                var ds = articleSyndication.querySelector("channel > pubDate").textContent;
            else if (articleSyndication.querySelector("channel > lastBuildDate") != null)
                var ds = articleSyndication.querySelector("channel > lastBuildDate").textContent;

            if (ds != null && ds != undefined) {
                var date = ds.substring(5, 7) + "-" + ds.substring(8, 11) + "-" + ds.substring(12, 16);
                feed.description = "Actualizado " + date;
            } else
                feed.description = "";

            feed.subtitle = articleSyndication.querySelector("channel > description").textContent;

            feed.itemsName = "item";
        }
        feed.pubDate = date;
        feed.backgroundImage = feed.logoUrl;
    }

    function getItemsFromXml(articleSyndication, feed) {
        var feedItems = [];

        var posts = articleSyndication.querySelectorAll(feed.itemsName);
        // Process each blog post.
        for (var postIndex = 0; postIndex < posts.length; postIndex++) {
            var post = posts[postIndex];
            // Get the title, author, and date published.
            var postTitle = post.querySelector("title").textContent;
            var link = post.querySelector("link").textContent;
            if (link == null || link == "") {
                link = post.querySelector("link").attributes.href.value;
            }
            var contentTag = null;
            var contentTagsUsed = ["encoded", "description", "content"];
            contentTagsUsed.forEach(function (t) {
                if (post.querySelector(t) != null && contentTag == null)
                    contentTag = t;
            });
            var imgInContent = /<img [^>]*src="([^"]*)"[^>]*\/>/.exec(post.querySelector(contentTag).textContent);

            if (feed.itemsName == "entry") {
                var postAuthor = post.querySelector("author > name").textContent;

                if (post.querySelector("published") != null)
                    var pds = post.querySelector("published").textContent;
                else if (post.querySelector("updated") != null)
                    var pds = post.querySelector("updated").textContent;

                var postDate = pds.substring(5, 7) + "-" + pds.substring(8, 10)
                    + "-" + pds.substring(0, 4);

                var imageUrl;
                if (post.querySelector("thumbnail") != null)
                    imageUrl = post.querySelector("thumbnail").attributes.url.value;
                else if (post.querySelector("img") != null)
                    imageUrl = post.querySelector("img").attributes.src.value;
                else if (imgInContent != null)
                    imageUrl = imgInContent[1];
                else
                    imageUrl = feed.logoUrl;

                // Process the content so that it displays nicely.
                var staticContent = toStaticHTML(post.querySelector(
                    contentTag).textContent);
            } else if (feed.itemsName == "item") {
                var postAuthor = feed.title;

                if (post.querySelector("pubDate") != null) {
                    var pds = post.querySelector("pubDate").textContent;
                    var postDate = pds.substring(5, 7) + "-" + pds.substring(8, 11) + "-" + pds.substring(12, 16);
                } else
                    var postDate = "";

                var imageUrl;

                if (post.querySelector("enclosure") != null)
                    imageUrl = post.querySelector("enclosure").attributes.url.value;
                else if (post.querySelector("img") != null)
                    imageUrl = post.querySelector("img").attributes.src.value;
                else if (imgInContent != null)
                    imageUrl = imgInContent[1];
                else
                    imageUrl = feed.logoUrl;

                // Process the content so that it displays nicely.
                var staticContent = toStaticHTML(post.querySelector(
                    contentTag).textContent);
            }

            // Store the post info we care about in the array.
            feedItems.push({
                group: feed, key: postTitle, title: postTitle,
                author: postAuthor, pubDate: postDate, backgroundImage: imageUrl,
                content: staticContent, link: link, postIndex: postIndex
            });
        }
        return feedItems;
    }

    function init(key, url, logoUrl) {
        this.key = key;
        this.url = url;
        this.logoUrl = logoUrl;
    }

    var instanceMembers = {
        getFeed: function () {
            var feed = {
                key: this.key,
                logoUrl: this.logoUrl,
                url: this.url,
            };

            return WinJS.xhr({ url: feed.url }).then(function (articlesResponse) {
                var articleSyndication = articlesResponse.responseXML;

                if (articleSyndication == null) {
                    var parser = new DOMParser();
                    articleSyndication = parser.parseFromString(articlesResponse.responseText, "application/xml");
                }

                getGroupInfoFromXml(articleSyndication, feed);
                return WinJS.Promise.wrap(getItemsFromXml(articleSyndication, feed));
            });
        },
    };

    var staticMembers = {};

    var FeedQuery = WinJS.Class.define(init, instanceMembers, staticMembers);

    // add to namespace
    WinJS.Namespace.define("Queries",
        {
            FeedQuery: FeedQuery
        }
    );
})();